<template>
    <div class="info">
        <h3>入住配置</h3>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="入住期限" prop="checkInTime">
                    <el-date-picker type="datetimerange" :readonly="type === 'read'" v-model="checkInTime"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" :style="{ width: '100%' }"
                        start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" clearable
                        @change="hendleCheckInTime"></el-date-picker>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="费用期限" prop="feeTime">
                    <el-date-picker type="datetimerange" :readonly="type === 'read'" v-model="feeTime"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" :style="{ width: '100%' }"
                        start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" clearable
                        @change="hendleFeeTime"></el-date-picker>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="护理等级" prop="nursingLevelId">
                    <el-select v-model="formData.nursingLevelId" :disabled="type === 'read'" placeholder="请选择护理等级"
                        clearable :style="{ width: '100%' }" @change="handleNursing">
                        <el-option v-for="(item, index) in nursingLevelIdOptions" :key="index" :label="item.name"
                            :value="item.id" :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="入住床位" prop="bed">
                    <div v-if="type === 'read'">
                        {{ formData.bedNumber }}
                    </div>
                    <el-cascader v-else v-model="formData.bed" :options="bedIdOptions" :props="bedProps"
                        @change="handleFloor" :style="{ width: '100%' }" placeholder="请选择入住床位" clearable
                        :show-all-levels="true" filterable :separator="' / '" :collapse-tags="false"></el-cascader>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="押金" prop="deposit">
                    <el-input v-model="formData.deposit" :disabled="type === 'read'" type="text" placeholder="请输入押金"
                        clearable :style="{ width: '100%' }"></el-input>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="护理费用" prop="nursingFee">
                    <el-input-number v-model="formData.nursingFee" placeholder="护理费用"
                        :disabled='true'></el-input-number>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="床位费用" prop="bedFee">
                    <el-input-number v-model="formData.bedFee" placeholder="床位费用" :disabled='true'></el-input-number>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="其他费用" prop="otherFees">
                    <el-input-number v-model="formData.otherFees" :disabled="type === 'read'"
                        placeholder="其他费用"></el-input-number>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="医保支付" prop="insurancePayment">
                    <el-input-number :disabled="type === 'read'" v-model="formData.insurancePayment"
                        placeholder="医保支付"></el-input-number>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="政府补贴" prop="governmentSubsidy">
                    <el-input-number :disabled="type === 'read'" v-model="formData.governmentSubsidy"
                        placeholder="政府补贴"></el-input-number>
                </el-form-item>
            </el-col>

        </el-row>
    </div>
</template>
<script setup>
import { getAllLevels } from '@/api/nursing/level'
import { getFloorBed, getAvailableBeds, getBedDetails, getRootById } from '@/api/nursing/floor'
import {
    ElMessage
}
    from 'element-plus'
import { onMounted, onUnmounted } from 'vue'
import emitter from '@/utils/eventBus'
const props = defineProps({
    formData: {
        type: Object,
        required: true
    },
    type: {
        type: String,
        default: ''
    }
})
const nursingLevelIdOptions = ref([])

const bedIdOptions = ref([])

const refreshBedOptions = async () => {
    // 获取所有空闲床位
    const res = await getAvailableBeds();
    if (res.code === 200) {
        bedIdOptions.value = res.data;
    }
}

onMounted(() => {
    //初始化护理等级
    getAllLevels().then((res) => {
        nursingLevelIdOptions.value = res.data;
    })
    refreshBedOptions();

    // 监听护理等级变动事件
    emitter.on('nursingLevelChanged', refreshNursingLevels);
})

onUnmounted(() => {
    emitter.off('nursingLevelChanged', refreshNursingLevels);
});

const refreshNursingLevels = () => {
    getAllLevels().then((res) => {
        nursingLevelIdOptions.value = res.data;
    });
};
//选择床位之后，给属性赋值
//val===>['6','39','58']  第一个值为楼层id, 第二个为房间id,第三个为床位id
const handleFloor = (val) => {
    if (val && val.length >= 3) {
        props.formData.bedId = val[2];
        // 根据床位ID获取床位详细信息
        getBedDetails(val[2]).then((res) => {
            if (res.code === 200) {
                const bedInfo = res.data;
                props.formData.bedNumber = bedInfo.bedNumber;
                // 根据房间ID获取房间信息
                getRootById(val[1]).then((roomRes) => {
                    if (roomRes.code === 200) {
                        props.formData.floorName = roomRes.data.floorName;
                        props.formData.floorId = roomRes.data.floorId;
                        props.formData.bedFee = roomRes.data.price;
                        props.formData.price = roomRes.data.price;
                        props.formData.code = roomRes.data.code;
                        props.formData.roomId = roomRes.data.roomId;
                        console.log('选择的床位信息:', props.formData);
                    }
                }).catch((error) => {
                    console.error('获取房间信息失败:', error);
                })
            }
        }).catch((error) => {
            console.error('获取床位信息失败:', error);
        })
    } else {
        // 清空床位相关信息
        props.formData.bedId = null;
        props.formData.bedNumber = null;
        props.formData.floorName = null;
        props.formData.floorId = null;
        props.formData.bedFee = null;
        props.formData.price = null;
        props.formData.code = null;
        props.formData.roomId = null;
    }
}
//处理入住时间
const hendleCheckInTime = (val) => {
    if (val.length > 0) {
        props.formData.startDate = val[0];
        props.formData.endDate = val[1];
        props.formData.checkInTime = '1'
    }
}

//处理费用时间
const hendleFeeTime = (val) => {
    if (val.length > 0) {
        props.formData.feeStartDate = val[0];
        props.formData.feeEndDate = val[1];
        props.formData.feeTime = '1'
    }
}

//选择了护理等级之后，触发，给护理费用和护理名称赋值
const handleNursing = () => {
    if (props.formData.nursingLevelId) {
        //根据id从集合中找对应的护理等级对象
        const obj = nursingLevelIdOptions.value.find((item) => item.id === props.formData.nursingLevelId);
        console.log(obj)
        //给属性赋值
        props.formData.nursingFee = obj.fee;
        props.formData.nursingLevelName = obj.name;
    } else {
        props.formData.nursingCost = null;
    }
}

const bedOptions = ref([])
// props设置
const bedProps = {
  checkStrictly: false,
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: true,
  expandTrigger: 'click',
  multiple: false
}


const checkInTime = ref([]);
const feeTime = ref([]);

watch(
    props,
    () => {
        checkInTime.value = [props.formData.startDate, props.formData.endDate];
        feeTime.value = [props.formData.feeStartDate, props.formData.feeEndDate];
    },
    { immediate: true }
);

const checkInRules = [
    { required: true, message: '请选择入住期限', trigger: 'change' }
];
const feeTimeRules = [
    { required: true, message: '请选择费用期限', trigger: 'change' }
];
const nursingLevelIdRules = [
    { required: true, message: '请选择护理等级', trigger: 'change' }
];
const bedRules = [
    { required: true, message: '请选择入住床位', trigger: 'change' }
];
const depositRules = [
    { required: true, message: '请输入押金', trigger: 'blur' }
];

const rules = {
    checkInTime: checkInRules,
    feeTime: feeTimeRules,
    nursingLevelId: nursingLevelIdRules,
    bed: bedRules,
    deposit: depositRules,
    // 其他字段可按需添加
};

//暴露表单校验的数据给外面，给父组件
defineExpose({
    rules
})

</script>
<style></style>